<!-- 提交申请表 -->
<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="600px"
    @close="handleClose"
  >
    <el-form ref="form" :model="formData" label-width="100px">
      <el-form-item label="上传申请表">
        <el-upload
          :action="uploadFileUrl"
          :auto-upload="false"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :on-success="handleUploadSuccess"
          :file-list="fileList"
          accept=".jpg,.jpeg,.png,.pdf"
          :limit="1"
          :on-exceed="handleExceed"
          :disabled="uploading"
          class="upload-container"
        >
          <el-button size="small" type="primary" :loading="uploading"
            >上传申请表</el-button
          >
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" :loading="submitting" @click="submit"
        >提 交</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  name: "SubmitApplicationForm",
  props: {
    // 是否显示对话框
    visible: {
      type: Boolean,
      default: false,
    },
    // 对话框标题
    dialogTitle: {
      type: String,
      default: "提交申请表",
    },
    // 初始文件数据（用于编辑时回显）
    initialFile: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      formData: {
        file: null,
      },
      fileList: [],
      uploadedFile: null,
      uploading: false,
      submitting: false,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 完整上传地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  watch: {
    // 监听visible变化，当显示对话框时初始化数据
    visible(val) {
      if (val) {
        this.initData();
      }
    },
  },
  methods: {
    /**
     * 初始化数据
     */
    initData() {
      this.formData = {
        file: null,
      };
      this.fileList = [];
      this.uploadedFile = null;

      // 如果有初始文件数据，则设置
      if (this.initialFile) {
        this.fileList = [
          {
            name: this.initialFile.name,
            url: this.initialFile.url,
          },
        ];
        this.uploadedFile = this.initialFile.file;
      }
    },
    // 上传成功处理
    handleUploadSuccess(res, file) {
      this.$modal.closeLoading();
      if (res.code === 200) {
        this.$message.success("导入成功");
        this.$emit("import-success", {
          file: this.uploadedFile,
          mode: this.uploadMode,
        });
        this.cancel();
      } else {
        this.$modal.msgError(res.msg || "导入失败");
      }
      this.uploadLoading = false;
    },

    /**
     * 文件改变事件
     */
    handleChange(file, fileList) {
      this.fileList = fileList;
      this.uploadedFile = file.raw;
    },

    /**
     * 文件删除事件
     */
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.uploadedFile = null;
    },

    /**
     * 文件数量超过限制
     */
    handleExceed(files, fileList) {
      this.$message.warning("最多只能上传1个文件");
    },

    /**
     * 提交表单
     */
    submit() {
      if (!this.uploadedFile) {
        this.$message.warning("请上传申请表");
        return;
      }

      this.submitting = true;

      // 创建 FormData 对象
      const formData = new FormData();
      formData.append("file", this.uploadedFile);

      // 调用 API 提交
      uploadApplication(formData)
        .then((response) => {
          this.$message.success("提交成功");
          this.$emit("success", response.data);
          this.cancel();
        })
        .catch((error) => {
          this.$message.error("提交失败：" + error.message);
        })
        .finally(() => {
          this.submitting = false;
        });
    },

    /**
     * 取消操作
     */
    cancel() {
      this.visible = false;
      this.$emit("close");
    },

    /**
     * 关闭对话框
     */
    handleClose() {
      this.cancel();
    },
  },
};
</script>

<style scoped>
.upload-container {
  margin-top: 10px;
}

.el-upload--text {
  width: 100px;
  height: 32px;
  line-height: 32px;
  padding: 0;
  text-align: center;
  font-size: 14px;
}

.el-upload-list__item-name {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-upload-list__item-status-action {
  margin-left: 10px;
}
</style>

